package org.ysh.core.attachment;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfDocumentInfo;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import org.ysh.annotation.AdditionInfoResolver;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Date;

/**
 * PDF附加信息
 */
@AdditionInfoResolver(extensions = {"pdf"})
public class PdfAttachmentInfoResolver implements AttachmentAdditionInfoResolver {

    public static final String MORE_INFO_IP = "ip";
    public static final String MORE_INFO_USER = "user";
    public static final String MORE_INFO_TIME = "time";

    @Override
    public void addAdditionInfo(File tmpFile, AdditionInfo additionInfo) throws Exception {
        String replaceFile = tmpFile.getAbsolutePath() + "_bak";
        try(PdfDocument document = new PdfDocument(new PdfReader(tmpFile),new PdfWriter(new File(replaceFile)))){
            PdfDocumentInfo documentInfo = document.getDocumentInfo();
            documentInfo.setMoreInfo(MORE_INFO_IP, additionInfo.getHost());
            documentInfo.setMoreInfo(MORE_INFO_USER,additionInfo.getUserName());
            documentInfo.setMoreInfo(MORE_INFO_TIME,String.valueOf(additionInfo.getTime().getTime()));
        }
        if(tmpFile.delete() && new File(replaceFile).renameTo(tmpFile)){
            System.out.println("替换成功");
        }
    }

    @Override
    public AdditionInfo readAdditionInfo(InputStream in) throws Exception {
        try(PdfDocument document = new PdfDocument(new PdfReader(in))){
            PdfDocumentInfo documentInfo = document.getDocumentInfo();
            AdditionInfo additionInfo = new AdditionInfo();
            additionInfo.setHost(documentInfo.getMoreInfo(MORE_INFO_IP));
            additionInfo.setUserName(documentInfo.getMoreInfo(MORE_INFO_USER));
            additionInfo.setTime(new Date(Long.valueOf(documentInfo.getMoreInfo(MORE_INFO_TIME))));
            return additionInfo;
        }
    }

    public static void main(String[] args) throws Exception {
        PdfAttachmentInfoResolver pdfAttachmentInfo = new PdfAttachmentInfoResolver();
        File tmpFile = new File("D:\\document.pdf");
        AdditionInfo additionInfo = new AdditionInfo();
        additionInfo.setUserName("Lisssi");
        additionInfo.setTime(new Date());
        additionInfo.setHost("192.168.1.1");
        pdfAttachmentInfo.addAdditionInfo(tmpFile,additionInfo);

        additionInfo = pdfAttachmentInfo.readAdditionInfo(Files.newInputStream(tmpFile.toPath()));
        System.out.println(additionInfo);
    }
}
